/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.CategoryManager;

import javax.swing.JTable;
import resource.Category;
import resource.Macro;
import utilities.Codecs;
import utilities.DBConnector;
import utilities.Helper;
import utilities.Prompt;
import utilities.Validation;

/**
 *
 * @author fangchengjia
 */
public class CategoryManagerBase extends javax.swing.JFrame {
    private final DBConnector dbSession;
    private JTable categoryTable;
    public final String TABLE_MODEL[] = new String[] {
        Macro.CATEGORY_CLASS_L,
        Macro.CATEGORY_NAME_L,
        Macro.CATEGORY_ID_L
    };
    /**
     * Creates new form CategoryManager
     * @param dbSession
     */
    public CategoryManagerBase(DBConnector dbSession) {
        this.dbSession = dbSession;
    }
    
    public DBConnector getDBSession(){
        return dbSession;
    }
    
    public javax.swing.JTable getTargetTable(){
        return categoryTable;
    }
    
    public void setTargetTable(JTable categoryTable){
        this.categoryTable = categoryTable;
    }
    
    public void refresh(){
        Helper.refresh(dbSession, Macro.DB_CATEGORY, TABLE_MODEL,
                categoryTable);
    }
    
    public void searchByName(String value){
        Helper.searchBy(dbSession, Macro.DB_CATEGORY, TABLE_MODEL,
                categoryTable, Macro.CATEGORY_NAME_L, value);
    }
    
    public boolean inputCheck(Category category){
        return !Validation.empty("Name", category.getName()) &&
                Validation.validFormat("Class No.", category.getCallClass(),
                        Macro.REGEX_CLASS_NUM, "XX.dddd.dddd");
    }
    
    public void updateCategory(Category category){
        if (inputCheck(category)){
            String values[] = category.getValues();
            if (dbSession.check(Macro.DB_CATEGORY, 
                    String.format("%s='%s'", Macro.CATEGORY_ID_L, 
                        Codecs.encode(category.getId())))){                
                dbSession.update(Macro.DB_CATEGORY,
                        Helper.encodeValues(TABLE_MODEL, values),
                        String.format("%s='%s'", Macro.CATEGORY_ID_L, 
                            Codecs.encode(category.getId())));
                dispose();
            }
            else{
                Prompt.warning("The record doesn't exist.");
            }
        }
    }
}
